import React, { useCallback } from 'react';

import { Button, ButtonProps, Tooltip } from 'antd';
import classnames from 'classnames';
import {
  ICalculateType,
  IEditorOperateType,
  IOperateGroupItem,
} from './CodeEditorConfig';
import { EditorToolbarLayout } from './CodeEditorStyle';

interface GroupBasicProps {
  shape?: ButtonProps['shape'];
  type?: ButtonProps['type'];
  size?: ButtonProps['size'];
  callback: (value: any, type?: IEditorOperateType | ICalculateType) => void;
  className?: string;
  style?: React.CSSProperties;
}

interface GroupItemProps extends GroupBasicProps {
  data: IOperateGroupItem[];
}
interface GroupProps extends GroupBasicProps {
  data: IOperateGroupItem[][];
}

export const CodeEditorToolbarGroup: React.FC<GroupItemProps> = (props) => {
  const {
    data,
    shape,
    type = 'text',
    size,
    callback,
    className,
    style,
  } = props;

  return (
    <div
      className={classnames('editor-toolbar-group', className)}
      style={{ ...style }}>
      {data?.map((item, idx) => {
        return (
          <div key={idx} className="editor-toolbar-group-item">
            <Tooltip title={item?.label}>
              <Button
                shape={shape}
                type={type}
                size={size}
                onClick={() => callback(item?.value, item?.type)}>
                <span
                  style={{
                    ...item?.style,
                    display: 'inline-flex',
                    alignItems: 'center',
                  }}>
                  {item?.text || item?.label}
                </span>
              </Button>
            </Tooltip>
          </div>
        );
      })}
    </div>
  );
};

export const CodeEditorToolbar: React.FC<GroupProps> = (props) => {
  const {
    data,
    shape,
    type = 'text',
    size,
    className,
    style,
    callback,
  } = props;

  const onClickChange = useCallback(
    (value: string, type?: IEditorOperateType | ICalculateType) => {
      if (callback) {
        callback(value, type);
      }
    },
    [callback],
  );

  return (
    <EditorToolbarLayout
      className={classnames('editor-toolbar', className)}
      style={{ ...style }}>
      {data?.map((item, idx) => {
        return (
          <CodeEditorToolbarGroup
            key={idx}
            data={item}
            shape={shape}
            type={type}
            size={size}
            callback={onClickChange}
          />
        );
      })}
    </EditorToolbarLayout>
  );
};
